import axios from 'axios'
import { Request as Http } from './http'
import { useMessage } from '@/hooks/element/useMessage'
import { router } from '@/router'

// 后端请求状态码
export const RES_CODE = {
  CANCELED: -1, // 已取消请求
  SUCCESS: 0, // 成功
  UN_LOGIN: 103, // 未登录逻辑
  NO_PERMISSION: 110, // 无权限
  COMMON_ERROR: 10000, // 通用异常
}

const AMessage = useMessage()

export const Request = new Http({
  config: {
    withCredentials: true,
    headers: {
      'Content-Type': 'application/json;charset=UTF-8',
    },
    timeout: 10000,
    errorTips: true,
    baseURL: `${location.origin}${import.meta.env.VITE_API_PREFIX}` || '',
  },
  requestInterceptor: (config) => {
    config.headers = config.headers || {}
    config.headers['App-Code'] = import.meta.env.VITE_APP_CODE
    config.headers['Hos-Code'] = import.meta.env.VITE_HOS_CODE
    config.headers['Client-Channel'] = 'Web'
    config.headers['D-U-Ticket'] = localStorage.getItem('U_TICKET') || ''

    return config
  },
  responseInterceptorCatch: (error) => {
    if (axios.isCancel(error))
      return Promise.resolve({ code: RES_CODE.CANCELED })

    return Promise.reject(error)
  },

  responseCallback(response, resolve, reject, options) {
    if (import.meta.env.VITE_IS_MOCK) {
      // mock 模式下直接返回请求数据
      resolve(response)
      return
    }

    const { code, data, message } = response

    if (code === RES_CODE.UN_LOGIN) {
      AMessage.error({
        message: '登录失效，请求重新登录',
      })
      reject(data)
      router.push('/login')
      return
    }

    //
    if (code === RES_CODE.SUCCESS) {
      resolve(data)
      return
    }

    if (code === RES_CODE.CANCELED)
      reject({})

    if ((code === RES_CODE.NO_PERMISSION || code === RES_CODE.COMMON_ERROR) && options.errorTips) {
      reject(data)
      AMessage.error(message)
      return
    }

    reject(response)
  },
})
